package org.aplombh.java.leetcode.all;

public class _2两数相加 {
}

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution2_1 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode listNode = new ListNode();
        ListNode l = listNode;
        int r = 0;
        while (l1 != null && l2 != null) {
            l.val = (l1.val + l2.val + r) % 10;
            r = (l1.val + l2.val + r) / 10;

            l1 = l1.next;
            l2 = l2.next;

            // 同时为空直接结束
            if (l1 == null && l2 == null)
                break;

            l.next = new ListNode();
            l = l.next;

            // 只有一个为空还得新创建节点
            if (l1 == null || l2 == null)
                break;
        }

        while (l1 != null) {
            l.val = (l1.val + r) % 10;
            r = (l1.val + r) / 10;

            l1 = l1.next;

            if (l1 == null)
                break;

            l.next = new ListNode();
            l = l.next;

        }
        while (l2 != null) {
            l.val = (l2.val + r) % 10;
            r = (l2.val + r) / 10;
            l2 = l2.next;
            if (l2 == null)
                break;
            l.next = new ListNode();
            l = l.next;

        }

        if (r != 0) {
            l.next = new ListNode();
            l = l.next;
            l.val = r;
        }
        return listNode;
    }


}